const app=require('./ajax.js');
const config=require('./config.js');

/**
 * 请求
 */
function post(url,data){
    return new Promise((resolve,reject)=>{
        wx.request({
            url: config.ServerUrl+url,
            data:data||{},
            header:{
                'content-type':'Application/json'
            },
            method:'POST',
            dataType:'json',
            responseType:'text',
            success:function(res){
                const result=res.data;
                if(result.code==1){
                    resolve(result.data);
                }else if(result.code==2){
                    reject(result.msg);
                }else{
                    reject('服务忙');
                }
            },
            fail:function(err){
                if(config.debug){
                    console.log(err);
                    reject("服务忙");
                }
            }
        })
    })
};

const city={
    /**
     * 初始化数据
     */
    init:(that)=>{
        //设置省的数据，cityName:that.data.provinces[0].name
        city.provinces(that,()=>{
            that.setData({cityId:that.data.provinces[0].id});
            //设置市的数据
            city.citys(that,()=>{
                that.setData({areaId:that.data.citys[0].id,areaName:that.data.citys[0].name});
                //设置区的数据
                city.areas(that,()=>{});
            })
        })
    },
    /**
     * 获取省
     */
    provinces:(that,cb)=>{
        app.doPost('/wxcity/searchCityByLevel',{level:1},(data)=>{
            if(data.code==1){
                let provices=data.data;
                that.setData({provinces});
                cb(provices);
            }else{
                wx.showToast({
                    title: data.msg||'访问忙',
                    image:'../pages/image/icon/error.png'
                })
            }
        })
    },
    /**
     * 获取省集合
     */
    getProvinceList:()=>{
        return post('/wxcity/searchCitysByPid',{id});
    }
}